package com.junsi.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

public class FileUtil {
	
	public static String filePpload(MultipartFile file,String path){
		

        String fileName = new Date().getTime()+""+file.getOriginalFilename();  
       // String fileName = new Date().getTime()+".png";  
        System.out.println(path);  
        File targetFile = new File(path, fileName);  
        
        if(!targetFile.exists()){  
            targetFile.mkdirs();  
        }  
  
        try {  
            file.transferTo(targetFile);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        
        String fileNames = path+"\\"+fileName;
        
        return fileNames;
	}
	
	/**
	 * 用IO流上传文件
	 * @param file
	 * @return 成功返回文件的名字，失败返回:图片上传失败
	 * @throws IOException
	 */
	public static String fileUploe(CommonsMultipartFile file) throws IOException{
		try {
			String fileName = new Date().getTime()+file.getOriginalFilename();
            OutputStream os=new FileOutputStream(DownFile.PATH+fileName);
            InputStream is=file.getInputStream();
            int temp;
            while((temp=is.read())!=(-1))
            {
                os.write(temp);
            }
           os.flush();
           os.close();
           is.close();
           return fileName;
         
        } catch (FileNotFoundException e) {
        	return "图片上传失败";
        }
	}
	
	/**
	 * 用IO流上传文件
	 * @param file
	 * @return 成功返回文件的名字
	 * @throws IOException
	 */
	public static String Uploadfile(CommonsMultipartFile file) throws IOException{
		try {
			String fileName = new Date().getTime()+file.getOriginalFilename();
            OutputStream os=new FileOutputStream("c:/files/"+fileName);
            InputStream is=file.getInputStream();
            int temp;
            while((temp=is.read())!=(-1))
            {
                os.write(temp);
            }
           os.flush();
           os.close();
           is.close();
           return fileName;
         
        } catch (FileNotFoundException e) {
        	return "上传失败";
        }
	}
}
